import { apiLogin, initCode, getCodeImg } from './services/login';
import { useLayoutEffect, useState, useEffect } from 'react';
import _ from 'lodash';
import { history } from 'umi';
import type { IUser, IUserInfo } from './types/user';
import goodStorage from 'good-storage';
import Cookies from 'js-cookie';

const localStorageTokenKey = '__auth_token__';
const localStorageUserKey = '__auth_user__';

export const getToken = () => goodStorage.get(localStorageTokenKey);
export const getUser = (): IUserInfo | null => {
  return goodStorage.get(localStorageUserKey, null);
};

export const removeCookie = () => {
  Cookies.remove('username');
  Cookies.remove('password');
};

export const setRememberInfo = ({
  isRemember,
  username,
  password,
}: Pick<IUser, 'isRemember' | 'username' | 'password'>) => {
  if (isRemember) {
    Cookies.set('username', username, {
      expires: 30,
    });
    Cookies.set('password', password, {
      expires: 30,
    });
  } else {
    removeCookie();
  }
};

export const getRememberInfo = () => {
  const username = Cookies.get('username') ?? '';
  const password = Cookies.get('password') ?? '';
  if (!username && !password) {
    return false;
  }
  return { username, password, isRemember: true };
};

export const setTokenAndUser = (token: string, user: IUserInfo) => {
  goodStorage.set(localStorageTokenKey, token);
  goodStorage.set(localStorageUserKey, { realname: user.realname });
};

export const login = async (params: IUser, url: string, callback: () => void) => {
  try {
    const res = await apiLogin(params);
    if (res.success) {
      const token: string = res.data.token;
      const user = res.data.user;
      setTokenAndUser(token, user);
      setRememberInfo({
        isRemember: params.isRemember,
        username: params.username,
        password: params.password,
      });
      history.push(url);
      return token;
    }
  } catch {
    callback();
  }
};

export const logout = () => {
  goodStorage.remove(localStorageTokenKey);
  goodStorage.remove(localStorageUserKey);
  history.push(`/login`);
};

export const useCaptcha = () => {
  const [captchaImg, setCaptchaImg] = useState('');
  const [captchaId, setCaptchaId] = useState('');

  const getCode = _.debounce(async () => {
    const { data = '' } = await initCode();
    if (data) {
      setCaptchaId(data);
      const resImg = await getCodeImg(data);
      setCaptchaImg(window.URL.createObjectURL(resImg));
    }
  }, 200);

  useEffect(() => {
    getCode();
  }, []);

  return {
    captchaImg,
    getCode,
    captchaId,
    login,
  };
};
